<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>添加/编辑商品</title>
    <link rel="stylesheet" href="https://www.layuicdn.com/layui-v2.5.6/css/layui.css" media="all">
    <style>
        .product-container {
            padding: 20px;
        }

        .product-container {
            background-color: #fff;
        }

        .product-container form {
            width: 1500px;
            margin: 0 auto;
            padding: 30px;
            border: 1px solid #eee;
        }

        /* .product-container form .layui-form-item {
            width: 700px;
        } */
        #moreUpload img,
        #moreUpload div {
            width: 80px;
            height: 80px;
            margin-right: 4px;
            position: relative;
        }

        #moreUpload div {
            border: 1px dashed #ccc;
        }

        #moreUpload div::before {
            position: absolute;
            bottom: 0;
            left: 0;
            content: '点击图片删除';
            width: 100%;
            height: 30%;
            font-size: 12px;
            text-align: center;
            color: #fff;
            background-color: rgba(0, 0, 0, .6);
            z-index: 1;
        }

        #moreUpload div:nth-of-type(1)::before {
            position: absolute;
            bottom: 0;
            left: 0;
            content: '主图';
            width: 100%;
            height: 30%;
            font-size: 12px;
            text-align: center;
            color: #fff;
            background-color: #FF5722;
            z-index: 1;
        }

        .layui-card-body ul {
            display: flex;
            justify-content: space-between;
            border-bottom: 1px solid #ccc;
            padding: 8px 0;
            padding-right: 10px;
        }

        .layui-card-body ul li {
            flex: 1;
            text-align: center;
        }

        .layui-card-body ul li input {
            width: 50px;
            padding: 4px 6px;
            box-sizing: border-box;
            border-radius: 6px;
            border: 1px solid #ccc;
            text-align: center;
        }

        .layui-card-body ul li:first-child input {
            width: 120px;
        }

        .info {
            position: relative;
        }

        .addInput {
            position: absolute;
            right: -16px;
            bottom: 10px;
            cursor: pointer;
        }

        .gg-label {
            display: flex;
            align-items: center;
        }

        .gg-label li {
            margin: 0 10px;
        }

        .layui-badge {
            line-height: 15px;
            padding: 10px;
            border-radius: 5px;
        }

        .gglist-container {
            margin-left: 36px;
            margin-bottom: 30px;
        }

        .gglist-container .items {
            margin: 10px 0;
        }
    </style>
</head>

<body>
    <div class="product-container">
        <div style="display: flex;align-items: center;font-size: 17px;"><i class="layui-icon layui-icon-left goBack"
                style="font-size: 30px; color: #333;"></i><span class="goBack">返回列表</span></div>
        <form class="layui-form" lay-filter="product">
            <fieldset class="layui-elem-field layui-field-title">
                <legend>基本信息</legend>
            </fieldset>

            <div class="layui-form-item">
                <label class="layui-form-label"><span style="color:red; font-size:16px;">* </span>商品名称</label>
                <div class="layui-input-block">
                    <input type="text" name="goodsName" lay-verify="required" lay-reqtext="商品名称是必填项，岂能为空？"
                        placeholder="请输入商品名称" autocomplete="off" class="layui-input">
                </div>
            </div>


            <div class="layui-form-item">
                <label class="layui-form-label"><span style="color:red; font-size:16px;">* </span>商品分类</label>
                <div class="layui-input-block">
                    <select name="categoryId" lay-verify="required" id="classify">
                        <option value=""></option>
                    </select>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">商品简介</label>
                <div class="layui-input-block">
                    <textarea placeholder="请输入内容" name="des" class="layui-textarea"></textarea>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label"><span style="color:red; font-size:16px;">* </span>主图</label>
                <div class="layui-input-block">
                    <div class="layui-upload">
                        <blockquote class="layui-elem-quote layui-quote-nm"
                            style="display: flex;align-items: center; width: 655px;">
                            <div class="layui-upload-list" id="moreUpload"
                                style="margin-top: 10px; display: flex;align-items: center;"></div>
                            <button type="button" style="width: 80px; height: 80px; text-align: center;"
                                class="layui-btn layui-btn-primary" id="uploadBtn"><i style="font-size: 28px;"
                                    class="layui-icon"></i></button>
                        </blockquote>
                        <input type="hidden" name="skuImgUrl" id="skuImgUrl">
                    </div>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">积分商品</label>
                <div class="layui-input-block" style="display:flex;">
                    <input type="checkbox" name="integralStatus" lay-filter="switchTest" lay-skin="switch" lay-text="ON|OFF">
                    <input type="text" name="integral" id="inputJF" style="width: 300px; margin-left: 30px;display: none;" lay-reqtext="积分价格"
                        placeholder="请输入积分价格" autocomplete="off" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">单人购买数量限制</label>
                <div class="layui-input-block" style="display:flex;">
                    <input type="checkbox" name="payNumLimitStatus" lay-filter="switchTest2" lay-skin="switch" lay-text="ON|OFF">
                    <input type="text" name="payNumLimit" id="inputJF2" style="width: 300px; margin-left: 30px;display: none;" lay-reqtext="单人购买数量"
                           placeholder="请输入单人购买数量" autocomplete="off" class="layui-input">
                </div>
            </div>
            

            <fieldset class="layui-elem-field layui-field-title" style="margin-top: 50px;">
                <legend>价格库存</legend>
            </fieldset>

            <div class="layui-form-item">
                <label class="layui-form-label">添加规格：</label>
                <div class="layui-input-block">
                    <button type="button" id="addNewGg" class="layui-btn">添加新规格</button>
                    <button type="button" id="drawTable" class="layui-btn layui-btn-normal">立即生成</button>
                </div>
            </div>

            <div class="layui-form-item" id="ggInput" style="display:flex; align-items: center;">
                <label class="layui-form-label">规格名：</label>
                <div class="layui-input-block" style="margin-left:0;">
                    <input type="text" id="skuType" placeholder="请填写规格名" autocomplete="off" class="layui-input">
                </div>

                <label class="layui-form-label">规格值</label>
                <div class="layui-input-block" style="margin-left:0;">
                    <input type="text" id="ggVal" placeholder="请填写规格值" autocomplete="off" class="layui-input">
                </div>

                <button type="button" class="layui-btn layui-btn-normal layui-btn-sm" id="addGgOk"
                    style="margin-left:20px">确定</button>
                <button type="button" class="layui-btn layui-btn-danger layui-btn-sm" id="addGgCancel">取消</button>
            </div>

            <ul class="gglist-container">

            </ul>

            <div class="layui-form-item filed-table">
                <label class="layui-form-label" style="width: 81px;"><span style="color:red; font-size:16px;">* </span>商品属性：</label>
                <div class="layui-input-block">
                    <div class="layui-col-md6">
                        <div class="layui-card" style="border: 1px solid #ccc; width: 690px;">
                            <div class="layui-card-body">
                                <ul>
                                    <li id="tabHeader">售价</li>
                                    <li>原价</li>
                                    <li>库存</li>
                                    <li>操作</li>
                                </ul>
                                <div class="info">
                                    <div class="info-input" id="tabs">

                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">商品编码</label>
                <div class="layui-input-block">
                    <input type="text" disabled name="spuNo" placeholder="自动生成无须填写" autocomplete="off"
                        class="layui-input">
                </div>
            </div>

            <fieldset class="layui-elem-field layui-field-title" style="margin-top: 50px;">
                <legend>商品介绍</legend>
            </fieldset>

            <textarea id="productDetails"></textarea>
            <div class="layui-form-item" style="text-align:center; margin-top: 30px;">
                <div class="layui-input-block" style="margin-left: 0;">
                    <button type="submit" class="layui-btn" lay-submit="" lay-filter="addProduct">立即提交</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </div>


</body>

<script src="https://cdn.bootcdn.net/ajax/libs/layui/2.5.7/layui.all.min.js"></script>
<script src="../utils.js"></script>
<script src="./layedit.js"></script>

<script>
    layui.use(['upload', 'form', 'jquery', 'layedit'], function () {
        var upload = layui.upload,
            form = layui.form,
            $ = layui.jquery,
            layedit = layui.layedit;
        var editContext = "";
        var uploadArr = [];
        var ggList = [];
        var skuLists = [];
        var listaaa = [];

        $("#ggInput, #drawTable, .filed-table").hide();

        $("#addNewGg").on("click", function () {
            $(this).hide();
            $("#ggInput").show();
        })
        renderGG(ggList)


        // sku遍历工具类
        function getSkuData(skuArr = [], i, list) {
            for (let j = 0; j < list[i].length; j++) {
                if (i < list.length - 1) {
                    skuArr[i] = list[i][j]
                    getSkuData(skuArr, i + 1, list) // 递归循环
                } else {
                    skuLists.push([...skuArr, list[i][j]]) // 扩展运算符，连接两个数组
                }
            }
        }

        // 渲染规格
        function renderGG(ggList) {
            if (ggList.length > 0) {
                $("#drawTable").show()
            }

            $(".gglist-container").empty();
            $.each(ggList, function (index, item) {
                var str = ''
                $.each(item.specsList, function (i, t) {
                    str += `
                            <li>
                                <span class="layui-badge layui-bg-gray" style="font-size: 14px">
                                    ${t.skuTitle}
                                    <span class="removeChildGG" style="font-size: 18px; padding: 4px; cursor:pointer;">×</span>
                                </span>
                                
                            </li>
                            
                        `
                })

                $(".gglist-container").append(`
                    <li class="items">
                        <div style="margin-bottom:10px;">
                            <span>${item.skuType}</span>
                            <span style="font-size: 18px margin-left: 10px; cursor:pointer;" class="parentRemove">ⓧ</span>
                        </div>
                        <ul class="gg-label">
                            ${str}
                            <li style="display:flex;">
                                <input type="text" placeholder="请输入属性值" autocomplete="off" style="width:120px" class="layui-input">
                                <button type="button" style="border-left:0" class="layui-btn layui-btn-primary childBtn">添加</button>
                            </li>
                        </ul>
                    </li>
                `)

            })

            // 添加子规格
            $(".childBtn").on("click", function () {
                let inputVal = $(this).prev().val();
                if (inputVal) {
                    let index = $(this).parent().parent().parent().index()
                    ggList[index].specsList.push({skuTitle: inputVal});
                    console.log(ggList, "-----ggList----");
                    renderGG(ggList)
                }
            })

            // 删除规格
            $(".parentRemove").on("click", function () {
                ggList.splice($(this).parent().parent().index(), 1);
                renderGG(ggList);
            })

            // 删除子规格的标签
            $(".removeChildGG").on("click", function () {
                let index = $(this).parent().parent().parent().parent().index();
                let childIndex = $(this).parent().parent().index();
                ggList[index].specsList.splice(childIndex, 1);

                renderGG(ggList);
            })

 

            // 生成表格
            $("#drawTable").off().on("click", function () {
                $("#tabHeader").prevAll().remove();
                $("#tabs").empty()
                skuLists = [];
                listaaa = [];
                
                
                renderSkuList();
            })
        }
        
        function delItem() {
            $(".removeItem").on("click", function() {
                $(this).parent().parent().remove()
            })
        }

        function renderSkuList(type) {
            if (type == "edit") {
                console.log(skuLists, "---skuLists----");
                if (skuLists.length) {
                    $(".filed-table").show();
                }
                if (!ggList.length) {
                    $.each([{ skuType: "" }, { skuType: "" }], function (i, el) {
                        $("#tabHeader").before(`
                            <li class="abc">${el.skuType}</li>
                        `)
                    })
                } else {
                    $.each(ggList, function (i, el) {
                        $("#tabHeader").before(`
                            <li class="abc">${el.skuType}</li>
                        `)
                    })
                }

                $.each(skuLists, function (f, t) {
                    var strt = "";
                    $.each(t.skuSpecsTypeList, function(s, d) {
                        $.each(d.skuSpecsList, function(a, b) {
                            console.log(b.skuTitle);
                            strt += `<li>${b.skuTitle}</li>`
                        })
                    })

                    $("#tabs").append(`
                        <ul>
                            ${strt}
                            <li><input lay-verify="required|number" value="${t.skuCurrPrice}" type="text"> 元</li>
                            <li><input lay-verify="required|number" value="${t.skuCostPrice}" type="text"> 元</li>
                            <li><input lay-verify="required|number" value="${t.skuNum}" type="text"> 件</li>
                            <li><button type="button" class="removeItem layui-btn layui-btn-danger layui-btn-xs">删除</button></li>  
                        </ul>
                    `)
                })

                delItem()

                return false;
            }

            $.each(ggList, function (i, el) {
                listaaa.push(el.specsList);
                $("#tabHeader").before(`
                    <li class="abc">${el.skuType}</li>
                `)
            })

            // 重构数组
            getSkuData([], 0, listaaa);

            if (skuLists.length) {
                $(".filed-table").show();
            }

            $.each(skuLists, function (f, t) {
                var doms = "";
                $.each(t, function (is, s) {
                    doms += `<li>${s.skuTitle}</li>`
                })

                $("#tabs").append(`
                    <ul>
                        ${doms}
                        <li><input lay-verify="required|number" type="text"> 元</li>
                        <li><input lay-verify="required|number" type="text"> 元</li>
                        <li><input lay-verify="required|number" type="text"> 件</li>
                        <li><button type="button" class="removeItem layui-btn layui-btn-danger layui-btn-xs">删除</button></li>  
                    </ul>
                `)
            })

            delItem()
        }

        $("#addGgOk").on("click", function () {
            if ($("#skuType").val() && $("#ggVal").val()) {
                ggList.push({
                    skuType: $("#skuType").val(),
                    specsList: [{ skuTitle: $("#ggVal").val() }]
                })
            }

            renderGG(ggList)

            $("#skuType").val("")
            $("#ggVal").val("")
            $("#addNewGg").show();
            $("#ggInput").hide();
        })

        $("#addGgCancel").on("click", function () {
            $("#addNewGg").show();
            $("#ggInput").hide();
            $("#skuType").val("");
            $("#ggVal").val("")
        })


        // 富文本配置
        editContext = layedit.build('productDetails', {
            height: 1000,
            uploadImage: {
                url: window.baseUrl + '/file/uploadFile',
                type: 'post'
            }
        });

        var spuId = getQueryString("spuId");

        // 编辑赋值
        function getProductDetails() {

            if (spuId) {
                ajax({
                    path: "/goods/getGoodsDetailForPc?spuId=" + spuId,
                    type: "GET",
                    success: function (res) {

                        form.val('product', res);
                        uploadArr = res.spuImgUrl.split(',');
                        renderImg();

                        // renderStatus (res.skuList)
                        ggList = res.specsTypeList || []
                        renderGG(ggList)
                        skuLists = res.skuList
                        renderSkuList("edit");

                        $(".spuIdFlag").show();
                        $("#frist-status").show();

                        if (res.integralStatus) {
                            $("#inputJF").show();
                            $("#inputJF").val(res.integral);
                        }
                        if (res.payNumLimitStatus) {
                            $("#inputJF2").show();
                            $("#inputJF2").val(res.payNumLimit);
                        }


                        try {
                            layedit.setContent(editContext, res.skuDetail);
                        } catch (error) {
                            console.log("发现异常，这个不重要我就不抛出了");
                        }


                    }
                }, $)
            }
        }

        ajax({
            path: "/goods/getCategoryList?length=99999999",
            type: "GET",
            success: function (res) {
                $.each(res.data, function (index, item) {
                    $('#classify').append('<option value="' + item.id + '">' + item.categoryName + '</option>')
                })
                getProductDetails();
                form.render();
            }
        }, $)


        // 删除图片
        function delImg() {
            $('#moreUpload div').off().on('click', function () {
                uploadArr.splice($(this).index(), 1);
                $("#skuImgUrl").val(uploadArr.join(","));
                renderImg();
            })
        }

        // 渲染图片
        function renderImg() {
            $('#moreUpload').empty();
            $.each(uploadArr, function (index, item) {
                $('#moreUpload').append('<div><img src="' + item + '" alt="" class="layui-upload-img"></div>')
            })
            delImg()
        }

        //多图片上传
        var htmlVal = $("#skuImgUrl").val();
        upload.render({
            elem: '#uploadBtn'
            , url: window.baseUrl + '/file/uploadFile' //改成您自己的上传接口
            , multiple: true
            , headers: {
                Authorization: localStorage.token
            }
            , before: function (obj) {
                loading = layer.load(1, {
                    shade: [0.6, '#000'] //0.1透明度的白色背景
                });

                //预读本地文件示例，不支持ie8
                obj.preview(function (index, file, result) {
                    $('#moreUpload').append('<div><img src="' + result + '" alt="' + file.name + '" class="layui-upload-img"></div>')
                });
            }
            , done: function (res) {
                //上传完毕
                uploadArr.push(res.data);
                layer.closeAll();
                var urlstr = uploadArr.join(',');
                layer.msg("上传成功！")
                $("#skuImgUrl").val(htmlVal ? (htmlVal + ',' + urlstr) : urlstr);
                // 重新排版图片
                renderImg();
                delImg();
            }
        });


        //监听指定开关
        form.on('switch(switchTest)', function(data){
            console.log(data);
            if (this.checked) {
                $("#inputJF").show();
            } else{
                $("#inputJF").hide();
            }
        });

        //监听指定开关
        form.on('switch(switchTest2)', function(data){
            console.log(data);
            if (this.checked) {
                $("#inputJF2").show();
            } else{
                $("#inputJF2").hide();
            }
        });


        // 提交
        form.on("submit(addProduct)", function (obj) {
            delete obj.field.file;

            obj.field.special = 0;
            obj.field.skuDetailImgUrl = "null";
            obj.field.skuCoversUrl = uploadArr[0];
            var skuArr = [];

            let abcList = JSON.parse(JSON.stringify(ggList));

            let aaaaa = $(".abc").length || 0;


            $.each($('.info-input ul'), function (index, el) {
                abcList.forEach((ist, ib) => {
                    ist.skuSpecsList = [];
                    ist.skuSpecsList.push({
                        skuTitle: $(el).children('li').eq(ib).html(),
                        skuType: ist.skuType
                    })
                    delete ist.specsList;
                })
                
                let a = {
                    // skuTitleType: $(el).children('li').eq(0).html(),
                    // skuTitle: $(el).children('li').eq(1).html(),
                    skuImgUrl: uploadArr.join(","),
                    skuCurrPrice: $(el).children('li').eq(aaaaa).children("input").val(),
                    skuCostPrice: $(el).children('li').eq(aaaaa + 1).children("input").val(),
                    skuNum: $(el).children('li').eq(aaaaa + 2).children("input").val(),
                    skuSpecsTypeList: JSON.parse(JSON.stringify(abcList)),
                    status: 1,
                    skuCoversUrl: uploadArr[0],
                    skuNo: obj.field.skuNo,
                    skuDetailImgUrl: "null"
                }

                if (spuId) {
                    a.id = $(el).attr('data-id');
                } else {
                    delete obj.field.spuNo
                }

                skuArr.push(a)
            })
            
            

            obj.field.skuList = skuArr;
            obj.field.integralStatus = obj.field.integralStatus == "on" ? 1 : 0;

            if (!obj.field.integralStatus) {
                obj.field.integral = 0;
            } else {
                if (!obj.field.integral || isNaN(obj.field.integral)) {
                    layer.msg("积分值不能为空，且必须是数字")
                    return false;
                }
            }
            obj.field.payNumLimitStatus = obj.field.payNumLimitStatus == "on" ? 1 : 0;
            if (!obj.field.payNumLimitStatus) {
                obj.field.payNumLimit = 0;
            } else {
                if (!obj.field.payNumLimit || isNaN(obj.field.payNumLimit)) {
                    layer.msg("积分值不能为空，且必须是数字")
                    return false;
                }
            }
            obj.field.status = 1;
            obj.field.skuDetail = layedit.getContent(editContext);

            if (spuId) {
                obj.field.id = spuId;
            }

            obj.field.specsTypeList = ggList;

            if (!skuArr.length) {
                layer.msg("请生成规格后在进行提交")    
                return false;
            }

            ajax({
                path: "/goods/saveOrUpdateGoods",
                data: obj.field,
                success: function (res) {
                    layer.msg("操作成功! ");
                    history.go(-1);
                }
            }, $)

            console.log(obj.field);
            return false;
        });
        $(".goBack").on('click', function () {
            window.history.go(-1);
        })
    });
</script>

</html>